const pool = require('../config/db');

/**
 * 获取指定店铺的产品列表
 * @param {Object} options - 查询选项
 * @param {number} options.storeId - 店铺ID
 * @param {string} options.sort - 排序字段
 * @param {number} options.asc - 升序(1)或降序(0)
 * @param {string} options.keyword - 搜索关键词
 * @param {number} options.page - 页码
 * @param {number} options.pageSize - 每页数量
 * @returns {Promise<Object>} - 产品列表和分页信息
 */
const getProductsByStoreId = async (options) => {
    try {
        const {
            storeId,
            sort = 'price',
            asc = 1,
            keyword = '',
            page = 1,
            pageSize = 10
        } = options;

        let query = `
            SELECT * FROM products 
            WHERE store_id = ?
        `;
        
        const params = [storeId];

        // 添加关键词搜索
        if (keyword) {
            query += ' AND (name LIKE ? OR description LIKE ?)';
            const likeKeyword = `%${keyword}%`;
            params.push(likeKeyword, likeKeyword);
        }

        // 添加排序
        if (sort === 'price') {
            query += ` ORDER BY price ${asc === 1 ? 'ASC' : 'DESC'}`;
        } else if (sort === 'sales') {
            query += ` ORDER BY sales ${asc === 1 ? 'ASC' : 'DESC'}`;
        } else if (sort === 'created_at') {
            query += ` ORDER BY created_at ${asc === 1 ? 'ASC' : 'DESC'}`;
        } else {
            query += ' ORDER BY price ASC'; // 默认按价格升序排序
        }

        // 计算总记录数
        const countQuery = `
            SELECT COUNT(*) as total 
            FROM products 
            WHERE store_id = ?
            ${keyword ? ' AND (name LIKE ? OR description LIKE ?)' : ''}
        `;
        
        const countParams = [storeId];
        if (keyword) {
            const likeKeyword = `%${keyword}%`;
            countParams.push(likeKeyword, likeKeyword);
        }
        
        const [countResult] = await pool.execute(countQuery, countParams);
        const total = countResult[0].total;

        // 添加分页
        const offset = (page - 1) * pageSize;
        query += ' LIMIT ? OFFSET ?';
        params.push(parseInt(pageSize), offset);

        const [rows] = await pool.execute(query, params);

        return {
            list: rows,
            pagination: {
                total,
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                totalPages: Math.ceil(total / pageSize)
            }
        };
    } catch (error) {
        console.error('[MODEL] 获取产品列表失败:', error);
        throw error;
    }
};

/**
 * 获取指定产品详情
 * @param {number} productId - 产品ID
 * @returns {Promise<Object>} - 产品详情
 */
const getProductById = async (productId) => {
    try {
        const [rows] = await pool.execute(
            `SELECT p.*, s.name as store_name, s.address as store_address 
             FROM products p
             JOIN stores s ON p.store_id = s.id
             WHERE p.id = ?`,
            [productId]
        );
        return rows[0];
    } catch (error) {
        console.error('[MODEL] 获取产品详情失败:', error);
        throw error;
    }
};

/**
 * 添加产品
 * @param {Object} productData - 产品数据
 * @returns {Promise<number>} - 新产品ID
 */
const addProduct = async (productData) => {
    try {
        const {
            store_id,
            name,
            description,
            price,
            original_price,
            stock,
            images,
            category,
            specifications,
            status
        } = productData;

        const [result] = await pool.execute(
            `INSERT INTO products 
             (store_id, name, description, price, original_price, stock, images, category, specifications, status, created_at) 
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
            [store_id, name, description, price, original_price, stock, JSON.stringify(images), category, JSON.stringify(specifications), status]
        );

        return result.insertId;
    } catch (error) {
        console.error('[MODEL] 添加产品失败:', error);
        throw error;
    }
};

/**
 * 更新产品信息
 * @param {number} productId - 产品ID
 * @param {Object} productData - 产品数据
 * @returns {Promise<boolean>} - 更新成功返回true
 */
const updateProduct = async (productId, productData) => {
    try {
        const {
            name,
            description,
            price,
            original_price,
            stock,
            images,
            category,
            specifications,
            status
        } = productData;

        await pool.execute(
            `UPDATE products 
             SET name = ?, 
                 description = ?, 
                 price = ?, 
                 original_price = ?, 
                 stock = ?, 
                 images = ?, 
                 category = ?, 
                 specifications = ?, 
                 status = ?,
                 updated_at = CURRENT_TIMESTAMP
             WHERE id = ?`,
            [name, description, price, original_price, stock, JSON.stringify(images), category, JSON.stringify(specifications), status, productId]
        );

        return true;
    } catch (error) {
        console.error('[MODEL] 更新产品失败:', error);
        throw error;
    }
};

/**
 * 删除产品
 * @param {number} productId - 产品ID
 * @returns {Promise<boolean>} - 删除成功返回true
 */
const deleteProduct = async (productId) => {
    try {
        await pool.execute(
            `DELETE FROM products WHERE id = ?`,
            [productId]
        );
        return true;
    } catch (error) {
        console.error('[MODEL] 删除产品失败:', error);
        throw error;
    }
};

/**
 * 创建产品订单
 * @param {Object} orderData - 订单数据
 * @returns {Promise<number>} - 订单ID
 */
const createProductOrder = async (orderData) => {
    try {
        const {
            user_id,
            store_id,
            product_id,
            quantity,
            price,
            total_price,
            deposit_amount,
            payment_method,
            status,
            shipping_address,
            contact_name,
            contact_phone,
            remarks
        } = orderData;

        const [result] = await pool.execute(
            `INSERT INTO product_orders 
             (user_id, store_id, product_id, quantity, price, total_price, deposit_amount, payment_method, status, shipping_address, contact_name, contact_phone, remarks, created_at) 
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
            [user_id, store_id, product_id, quantity, price, total_price, deposit_amount, payment_method, status, shipping_address, contact_name, contact_phone, remarks]
        );

        return result.insertId;
    } catch (error) {
        console.error('[MODEL] 创建产品订单失败:', error);
        throw error;
    }
};

/**
 * 获取用户的产品订单列表
 * @param {number} userId - 用户ID
 * @returns {Promise<Array>} - 订单列表
 */
const getUserProductOrders = async (userId) => {
    try {
        const [rows] = await pool.execute(
            `SELECT po.*, p.name as product_name, p.images as product_images, s.name as store_name
             FROM product_orders po
             JOIN products p ON po.product_id = p.id
             JOIN stores s ON po.store_id = s.id
             WHERE po.user_id = ?
             ORDER BY po.created_at DESC`,
            [userId]
        );
        return rows;
    } catch (error) {
        console.error('[MODEL] 获取用户产品订单列表失败:', error);
        throw error;
    }
};

/**
 * 获取店铺的产品订单列表
 * @param {number} storeId - 店铺ID
 * @returns {Promise<Array>} - 订单列表
 */
const getStoreProductOrders = async (storeId) => {
    try {
        const [rows] = await pool.execute(
            `SELECT po.*, p.name as product_name, u.name as user_name, u.phone as user_phone
             FROM product_orders po
             JOIN products p ON po.product_id = p.id
             JOIN users u ON po.user_id = u.id
             WHERE po.store_id = ?
             ORDER BY po.created_at DESC`,
            [storeId]
        );
        return rows;
    } catch (error) {
        console.error('[MODEL] 获取店铺产品订单列表失败:', error);
        throw error;
    }
};

/**
 * 更新产品订单状态
 * @param {number} orderId - 订单ID
 * @param {string} status - 新状态
 * @returns {Promise<boolean>} - 更新成功返回true
 */
const updateProductOrderStatus = async (orderId, status) => {
    try {
        await pool.execute(
            `UPDATE product_orders 
             SET status = ?, updated_at = CURRENT_TIMESTAMP
             WHERE id = ?`,
            [status, orderId]
        );
        return true;
    } catch (error) {
        console.error('[MODEL] 更新产品订单状态失败:', error);
        throw error;
    }
};

module.exports = {
    getProductsByStoreId,
    getProductById,
    addProduct,
    updateProduct,
    deleteProduct,
    createProductOrder,
    getUserProductOrders,
    getStoreProductOrders,
    updateProductOrderStatus
}; 